package com.macro.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.macro.mall.mapper.PmProdStockIoRecordMapper;
import com.macro.mall.mapper.PmProdStockMapper;
import com.macro.mall.mapper.PmProdStockTempMapper;
import com.macro.mall.model.*;
import com.macro.mall.product.constant.Constants;
import com.macro.mall.product.dto.QueryStockDoorDto;
import com.macro.mall.product.dto.ReturnServiceStockDto;
import com.macro.mall.product.service.PmProdSpecService;
import com.macro.mall.product.service.PmProdStockService;
import com.macro.mall.product.util.TaskUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class PmProdStockServiceImpl implements PmProdStockService {
    @Autowired
    private PmProdStockTempMapper pmProdStockTempMapper;
    @Autowired
    private PmProdStockMapper pmProdStockMapper;

    @Autowired
    private PmProdStockIoRecordMapper pmProdStockIoRecordMapper;
    @Autowired
    private PmProdSpecService pmProdSpecService;

    public ReturnServiceStockDto getServerStock(Long prodId, Long skuInstId, Integer siteId){
        ReturnServiceStockDto returnDto = new ReturnServiceStockDto();

        /**1.获取时间段集合***************************************************************/
        PmProdStockTempExample tempExample  = new PmProdStockTempExample();
        PmProdStockTempExample.Criteria tempCriteria = tempExample.createCriteria();
        if(prodId!=null){
            tempCriteria.andProdIdEqualTo(prodId);
        }
        tempCriteria.andTempStatusEqualTo(Constants.STATUS_VALID);
        tempExample.setOrderByClause(" temp_seq asc ");
        List<PmProdStockTemp> prodStockTempList =pmProdStockTempMapper.selectByExample(tempExample);
        if(prodStockTempList!=null && prodStockTempList.size()>0){
            PmProdStockTemp prodStockTemp=prodStockTempList.get(0);
            if(prodStockTemp!=null && !StringUtils.isBlank(prodStockTemp.getTempValue()) && prodStockTemp.getTempValue().length()>2){
                JSONArray array = JSON.parseArray(prodStockTemp.getTempValue());
                List<String> stockTimeList = new ArrayList<String>();
                if(array!=null && array.size()>0){
                    JSONObject obj = null;
                    for(int i=0;i<array.size();i++){
                        obj=array.getJSONObject(i);
                        stockTimeList.add(obj.getString("time"));
                    }
                }
                returnDto.setStockTimeList(stockTimeList);
            }
        }
        /**2.获取一段时间的库存***************************************************************/
        String today = TaskUtils.getDateAddDays(0);
        String endDay = TaskUtils.getDateAddDays(Constants.SHOW_STOCK_DAYS-1);
        PmProdStock qryProdStock = new PmProdStock();
        qryProdStock.setProdId(prodId);
        qryProdStock.setSkuInstId(skuInstId);
        qryProdStock.setDealershipId(Long.valueOf(siteId));
        List<PmProdStock> prodStockList =pmProdStockMapper.selectByDays(qryProdStock,today,endDay);

        JSONArray array = converData(prodStockList,today);
        returnDto.setStockArray(array);
        return returnDto;
    }

    private JSONArray converData(List<PmProdStock> prodStockList,String today){

        JSONArray array = new JSONArray();

        List<String> dayList = new ArrayList<String>();
        for (int i = 0; i < Constants.SHOW_STOCK_DAYS; i++) {
            dayList.add(TaskUtils.getDateAddDays(i));
        }

        Map<String, JSONObject> jsonMap = new HashMap<String, JSONObject>();
        JSONObject json =null;

        if(prodStockList!=null && prodStockList.size()>0){

            JSONArray detailArray =  new JSONArray();
            JSONObject detailObj = null;
            for(String curDay : dayList) {
                for (PmProdStock prodStock : prodStockList) {
                    if (curDay.equals(prodStock.getStockDate())) {
                        json = jsonMap.get(curDay);
                        Float stock;
                        if (json == null) {
                            json = new JSONObject();
                            json.put("stockDate", curDay);
                            if (curDay.equals(today)) {
                                json.put("week", "今天");
                            } else {
                                String[] daySplitArray = curDay.split("-");
                                json.put("week", TaskUtils.weekByDate(Integer.valueOf(daySplitArray[0]), Integer.valueOf(daySplitArray[1]), Integer.valueOf(daySplitArray[2])));
                            }
                            stock = prodStock.getCurrentStock();
                            detailArray = new JSONArray();
                            detailObj = new JSONObject();
                            detailObj.put("stockId",prodStock.getId());
                            detailObj.put("stockTime", prodStock.getStockTime());
                            detailObj.put("stock", prodStock.getCurrentStock());
                            detailArray.add(detailObj);
                        } else {
                            stock = prodStock.getCurrentStock() + json.getFloat("stock");
                            detailArray = json.getJSONArray("stockDetail");
                            detailObj = new JSONObject();
                            detailObj.put("stockId",prodStock.getId());
                            detailObj.put("stockTime", prodStock.getStockTime());
                            detailObj.put("stock", prodStock.getCurrentStock());
                            detailArray.add(detailObj);
                        }
                        json.put("stock", stock);
                        json.put("stockDetail", detailArray);

                        jsonMap.put(curDay, json);
                    }
                }
            }
            for(String curDay : dayList){
                json=(JSONObject)jsonMap.get(curDay);
                if(json==null){
                    json = new JSONObject();
                    json.put("stockDate", curDay);
                    if (curDay.equals(today)) {
                        json.put("week", "今天");
                    } else {
                        String[] daySplitArray = curDay.split("-");
                        json.put("week", TaskUtils.weekByDate(Integer.valueOf(daySplitArray[0]), Integer.valueOf(daySplitArray[1]), Integer.valueOf(daySplitArray[2])));
                    }
                    json.put("stock", 0);
                }
                array.add(json);
            }
        }
        return array;
    }

    public ReturnServiceStockDto getServerStockByDoor(QueryStockDoorDto queryDto){
        ReturnServiceStockDto returnDto = new ReturnServiceStockDto();

        String today = TaskUtils.getDateAddDays(0);
        String endDay = TaskUtils.getDateAddDays(Constants.SHOW_STOCK_DAYS-1);

        JSONArray salePrptyArray = new JSONArray();
        if(!StringUtils.isBlank(queryDto.getSalePrptyArray())){
            salePrptyArray =JSONObject.parseArray(queryDto.getSalePrptyArray());
        }
        JSONArray naturePrptyArray = new JSONArray();
        if(!StringUtils.isBlank(queryDto.getNaturePrptyArray())){
            naturePrptyArray =JSONObject.parseArray(queryDto.getNaturePrptyArray());
        }

        List<Map<String, Object>> stockList= pmProdSpecService.getSpecChannelByDoor(salePrptyArray, naturePrptyArray, "12", queryDto.getProdSpecId(), queryDto.getProvCode(),queryDto.getCityCode(),queryDto.getCountyCode(),today,endDay);

        JSONArray array = converDataByDoor(stockList,today);
        returnDto.setStockArray(array);
        return returnDto;
    }
    private JSONArray converDataByDoor( List<Map<String, Object>> stockList,String today){

        JSONArray array = new JSONArray();

        List<String> dayList = new ArrayList<String>();
        for (int i = 0; i < Constants.SHOW_STOCK_DAYS; i++) {
            dayList.add(TaskUtils.getDateAddDays(i));
        }

        Map<String, JSONObject> jsonMap = new HashMap<String, JSONObject>();
        JSONObject json =null;

        if(stockList!=null && stockList.size()>0){

            JSONArray detailArray =  new JSONArray();
            JSONObject detailObj = null;
            for(String curDay : dayList) {
                for (Map<String, Object> stockMap : stockList) {
                    String stockDate ="";
                    try {
                        stockDate = stockMap.get("stock_date").toString();
                    }catch (Exception ex){
                        continue;
                    }
                    if (curDay.equals(stockDate)) {
                        json = jsonMap.get(curDay);
                        Float stock;
                        Float stockInfo;
                        try{
                            stockInfo = Float.parseFloat(stockMap.get("stock_count").toString());
                        }catch (Exception e){
                            continue;
                        }
                        if (json == null) {
                            json = new JSONObject();
                            json.put("stockDate", curDay);
                            if (curDay.equals(today)) {
                                json.put("week", "今天");
                            } else {
                                String[] daySplitArray = curDay.split("-");
                                json.put("week", TaskUtils.weekByDate(Integer.valueOf(daySplitArray[0]), Integer.valueOf(daySplitArray[1]), Integer.valueOf(daySplitArray[2])));
                            }

                            stock = stockInfo;
                            detailArray = new JSONArray();
                            detailObj = new JSONObject();
                           //  detailObj.put("stockId",prodStock.getId());
                            detailObj.put("stockTime", stockMap.get("stock_time"));
                            detailObj.put("stock",stockInfo);
                            detailArray.add(detailObj);
                        } else {
                            stock = stockInfo + json.getFloat("stock");
                            detailArray = json.getJSONArray("stockDetail");
                            detailObj = new JSONObject();
                           //  detailObj.put("stockId",prodStock.getId());
                            detailObj.put("stockTime", stockMap.get("stock_time"));
                            detailObj.put("stock", stockInfo);
                            detailArray.add(detailObj);
                        }
                        json.put("stock", stock);
                        json.put("stockDetail", detailArray);

                        jsonMap.put(curDay, json);
                    }
                }
            }

        }
        for(String curDay : dayList){
            json=(JSONObject)jsonMap.get(curDay);
            if(json==null){
                json = new JSONObject();
                json.put("stockDate", curDay);
                if (curDay.equals(today)) {
                    json.put("week", "今天");
                } else {
                    String[] daySplitArray = curDay.split("-");
                    json.put("week", TaskUtils.weekByDate(Integer.valueOf(daySplitArray[0]), Integer.valueOf(daySplitArray[1]), Integer.valueOf(daySplitArray[2])));
                }
                json.put("stock", 0);
            }
            array.add(json);
        }
        return array;
    }
    /**
     * 增加库存 （暂时不用）
     * @param
     * @param
     * @param
     * @param
     * @param
     * @param
     * @return
     *
    public boolean addStock0(Long prodId, Long skuInstId, Integer siteId,String stockDate,String stockTime,Float changeStock,int stockIoType) throws Exception{

        PmProdStock record = new PmProdStock();
        record.setProdId(prodId);
        record.setSkuInstId(skuInstId);
        record.setDealershipId(Long.valueOf(siteId));
        record.setStockDate(stockDate);
        record.setStockTime(stockTime);

        List<PmProdStock> stockList = pmProdStockMapper.selectByPmProdStock(record);
        if(stockList == null || stockList.size()>1){
            throw new Exception("增加库存失败，暂无库存记录");
        }
        PmProdStock stockDB = stockList.get(0);

        Date curDate = new Date();
        //流水表
        PmProdStockIoRecord stockIoRecord = new PmProdStockIoRecord();
        stockIoRecord.setChannelId(stockDB.getChannelId());
        stockIoRecord.setChannelName(stockDB.getChannelName());
        stockIoRecord.setDealershipId(stockDB.getDealershipId());
        stockIoRecord.setDealershipName(stockDB.getDealershipName());
        stockIoRecord.setProdId(stockDB.getProdId());
        stockIoRecord.setProdCode(stockDB.getProdCode());
        stockIoRecord.setProdName(stockDB.getProdName());

        stockIoRecord.setSkuInstId(stockDB.getSkuInstId());
        stockIoRecord.setSkuCode(stockDB.getSkuCode());
        stockIoRecord.setSkuName(stockDB.getSkuName());
        stockIoRecord.setType(stockDB.getType());
        stockIoRecord.setStockDate(stockDB.getStockDate());
        stockIoRecord.setStockTime(stockDB.getStockTime());
        stockIoRecord.setIoAmount(changeStock);
        stockIoRecord.setUnit(stockDB.getUnit());

        stockIoRecord.setCreateTime(curDate);
        stockIoRecord.setIoType(stockIoType);

        pmProdStockMapper.addStockByPrimaryKey(stockDB.getId(),changeStock);
        pmProdStockIoRecordMapper.insert(stockIoRecord);

        return true;
    }
    /**
     * 增加库存
     * @param stockId
     * @param changeStock
     * @param
     * @return
     */
    public boolean addStock(Long stockId,Float changeStock) throws Exception{

        PmProdStock stockDB  = pmProdStockMapper.selectByPrimaryKey(stockId);
        if(stockDB == null){
            throw new Exception("增加库存失败，暂无库存记录");
        }
        PmProdStockIoRecord stockIoRecord = this.converStockIoRecord(stockDB,changeStock,Constants.STOCK_IO_TYPE_ADD,null);

        int stockCount=pmProdStockMapper.addStockByPrimaryKey(stockDB.getId(),changeStock);
        if(stockCount == 0 ){
            throw new Exception("增加库存失败！无更新记录");
        }else{
            pmProdStockIoRecordMapper.insert(stockIoRecord);
        }

        return true;
    }
    /**
     * 扣减库存
     * @param changeStock
     * @return
     */
//    public boolean deductStock(Long stockId,Float changeStock,String orderId) throws Exception{
//
//        PmProdStock stockDB  = pmProdStockMapper.selectByPrimaryKey(stockId);
//        if(stockDB == null){
//            throw new Exception("扣减库存失败，暂无库存记录");
//        }
//
//        //流水表
//        PmProdStockIoRecord stockIoRecord = this.converStockIoRecord(stockDB,changeStock * -1,Constants.STOCK_IO_TYPE_DEDUCT, orderId);
//
//        int stockCount=pmProdStockMapper.deductStockByPrimaryKey(stockDB.getId(),changeStock);
//        if(stockCount == 0 ){
//            throw new Exception("扣减库存失败！无更新记录");
//        }else{
//            pmProdStockIoRecordMapper.insert(stockIoRecord);
//        }
//
//        return true;
//    }
    /**
     * 回退库存
     * @param changeStock
     * @return
     */
//    public boolean rollbackStock(Long prodId, Long skuInstId, Integer siteId,String stockDate,String stockTime,Float changeStock,String orderId) throws Exception{
//
//        PmProdStock record = new PmProdStock();
//        record.setProdId(prodId);
//        record.setSkuInstId(skuInstId);
//        record.setDealershipId(Long.valueOf(siteId));
//        record.setStockDate(stockDate);
//        record.setStockTime(stockTime);
//
//        List<PmProdStock> stockList = pmProdStockMapper.selectByPmProdStock(record);
//        if(stockList == null || stockList.size()>1){
//            throw new Exception("回退库存失败，暂无库存记录");
//        }
//        PmProdStock stockDB = stockList.get(0);
//
//        PmProdStockIoRecordExample stockIoRecordExample  = new PmProdStockIoRecordExample();
//        PmProdStockIoRecordExample.Criteria stockIoRecordCriteria = stockIoRecordExample.createCriteria();
//        stockIoRecordCriteria.andProdIdEqualTo(prodId);
//        stockIoRecordCriteria.andSkuInstIdEqualTo(skuInstId);
//        stockIoRecordCriteria.andDealershipIdEqualTo(Long.valueOf(siteId));
//        stockIoRecordCriteria.andStockDateEqualTo(stockDate);
//        stockIoRecordCriteria.andStockTimeEqualTo(stockTime);
//        stockIoRecordCriteria.andOrderIdEqualTo(orderId);
//        stockIoRecordCriteria.andTypeEqualTo(Constants.STOCK_IO_TYPE_DEDUCT);
//        List<PmProdStockIoRecord>  prodStockIoRecordList =  pmProdStockIoRecordMapper.selectByExample(stockIoRecordExample);
//
//        PmProdStockIoRecord  stockIoRecord;
//        if(prodStockIoRecordList!=null && prodStockIoRecordList.size()>0){
//            PmProdStockIoRecord  stockIoRecordDB = prodStockIoRecordList.get(0);
//            stockIoRecord = this.converStockIoRecord(stockDB,stockIoRecordDB.getIoAmount() * -1,Constants.STOCK_IO_TYPE_ROLLBACK, orderId);
//        }else{
//            throw new Exception("回退库存失败，无扣减记录");
//        }
//
//        int stockCount=pmProdStockMapper.rollbackStockByPrimaryKey(stockDB.getId(),changeStock);
//        if(stockCount == 0 ){
//            throw new Exception("回退库存失败！无更新记录");
//        }else{
//            pmProdStockIoRecordMapper.insert(stockIoRecord);
//        }
//
//        return true;
//    }
    private PmProdStockIoRecord converStockIoRecord(PmProdStock stock,Float changeStock,int stockIoType,String orderId){

        Date curDate = new Date();
        PmProdStockIoRecord stockIoRecord = new PmProdStockIoRecord();
        //流水表
        stockIoRecord.setChannelId(stock.getChannelId());
        stockIoRecord.setChannelName(stock.getChannelName());
        stockIoRecord.setDealershipId(stock.getDealershipId());
        stockIoRecord.setDealershipName(stock.getDealershipName());
        stockIoRecord.setProdId(stock.getProdId());
        stockIoRecord.setProdCode(stock.getProdCode());
        stockIoRecord.setProdName(stock.getProdName());

        stockIoRecord.setSkuInstId(stock.getSkuInstId());
        stockIoRecord.setSkuCode(stock.getSkuCode());
        stockIoRecord.setSkuName(stock.getSkuName());
        stockIoRecord.setType(stock.getType());
        stockIoRecord.setStockDate(stock.getStockDate());
        stockIoRecord.setStockTime(stock.getStockTime());
        stockIoRecord.setIoAmount(changeStock);
        stockIoRecord.setUnit(stock.getUnit());

        stockIoRecord.setCreateTime(curDate);
        stockIoRecord.setIoType(stockIoType);
        stockIoRecord.setOrderId(orderId);
        stockIoRecord.setStockId(stock.getId());
        return stockIoRecord;
    }
    /**
     * 回退库存
     * @param
     * @return
     */
//    public boolean rollbackStockSimplify(String orderId) throws Exception{
//        PmProdStock stockDB = null;
//
//        PmProdStockIoRecordExample stockIoRecordExample  = new PmProdStockIoRecordExample();
//        PmProdStockIoRecordExample.Criteria stockIoRecordCriteria = stockIoRecordExample.createCriteria();
//        stockIoRecordCriteria.andOrderIdEqualTo(orderId);
//        stockIoRecordCriteria.andTypeEqualTo(Constants.STOCK_IO_TYPE_DEDUCT);
//        List<PmProdStockIoRecord>  prodStockIoRecordList =  pmProdStockIoRecordMapper.selectByExample(stockIoRecordExample);
//
//        PmProdStockIoRecord  stockIoRecord;
//        PmProdStockIoRecord  stockIoRecordDB;
//        Float changeStock;
//        if(prodStockIoRecordList!=null && prodStockIoRecordList.size()>0){
//            stockIoRecordDB = prodStockIoRecordList.get(0);
//
//            PmProdStock record = new PmProdStock();
//            record.setProdId(stockIoRecordDB.getProdId());
//            record.setSkuInstId(stockIoRecordDB.getSkuInstId());
//            record.setDealershipId(stockIoRecordDB.getDealershipId());
//            record.setStockDate(stockIoRecordDB.getStockDate());
//            record.setStockTime(stockIoRecordDB.getStockTime());
//
//            List<PmProdStock> stockList = pmProdStockMapper.selectByPmProdStock(record);
//            if(stockList == null || stockList.size()>1){
//                throw new Exception("回退库存失败，暂无库存记录");
//            }
//            stockDB = stockList.get(0);
//
//            stockIoRecord = this.converStockIoRecord(stockDB,stockIoRecordDB.getIoAmount() * -1,Constants.STOCK_IO_TYPE_ROLLBACK, orderId);
//        }else{
//            throw new Exception("回退库存失败，无扣减记录");
//        }
//
//        int stockCount=pmProdStockMapper.rollbackStockByPrimaryKey(stockDB.getId(),stockIoRecordDB.getIoAmount());
//        if(stockCount == 0 ){
//            throw new Exception("回退库存失败！无更新记录");
//        }else{
//            pmProdStockIoRecordMapper.insert(stockIoRecord);
//        }
//
//        return true;
//    }
}
